package com.wy.system.controller;

import com.wy.common.result.Result;
import com.wy.common.utils.DES;
import com.wy.common.utils.JwtHelper;
import com.wy.common.utils.MD5;
import com.wy.model.entity.User;
import com.wy.model.vo.LoginVo;
import com.wy.system.exception.MyException;
import com.wy.system.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

//用户登录接口
@Slf4j
@RestController
@RequestMapping("/admin/system/index")
public class IndexController {

  @Autowired
  private UserService userService;

  //login
  @PostMapping("login")
  public Result login(@RequestBody LoginVo loginVo) throws Exception {
    DES des = new DES();
    //根据username查询数据库
    User user = userService.getUserInfoByUserName(loginVo.getUsername());
    System.out.println(user+"=======================");
    //如果查询为空
    if (user == null){
      throw new MyException(20001,"用户不存在");
    }
    //判断密码是否一致
    String voPassword = loginVo.getPassword();
    String md5Password = MD5.encrypt(voPassword);
    System.out.println(md5Password);
    System.out.println(user.getPassword());
    if (!user.getPassword().equals(md5Password)){
      throw new MyException(20001,"用户密码不正确");
    }
    //判断用户状态是否可用
    if (user.getStatus().intValue() == 0){
      throw new MyException(20001,"该用户已被禁用");
    }

    //根据userid和username生成token字符串，通过map返回
    String token = JwtHelper.createToken(user.getId(), user.getUsername());

    Map<String,Object> map = new HashMap<>();
    map.put("token",token);
    return Result.ok(map);
  }

  //info
  @GetMapping("info")
  public Result info(HttpServletRequest request){
    //获取请求头token字符串
    String token = request.getHeader("token");
    //从token字符串获取用户名称（id）
    String username = JwtHelper.getUsername(token);
    //根据用户名称获取用户信息(基本信息 和 菜单权限 和 按钮权限数据)
    Map<String,Object> map = userService.getUserInfo(username);
    return Result.ok(map);
  }

}
